// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */

  // 简单的取出子分类的函数
  async getChild(id) {
    // 取出子id
    let child_arr = [];
    const child = await this.model('or_subjecttype').where({ pid: id }).getField('id');
    if (!think.isEmpty(child)) {
      for (var i = child.length - 1; i >= 0; i--) {
        child_arr.push(child[i]);
        child_arr = child_arr.concat(await this.getChild(child[i]));
      };
    };
    return child_arr;
  }

  // 制作inarray函数
  inArray(id, array) {
    if (!think.isEmpty(array)) {
      for (var i = 0; i < array.length; i++) {
        if (array[i] == id) {
          return true;
        };
      };
    };
    return false;
  }

  async subjectlistAction() {
    const page = this.post();
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const zt = page.zt;
    const shopid = this.userinfo.departmentid;

    const data = await this.model('or_subject')
      .alias('s')
      .field('s.*,b.name as bname,c.name as cname')
      .join('`think_or_brand` b on b.id=s.brandid')
      .join('`think_or_subjectcategory` c on c.id=s.categoryid')
      // .join('`think_or_subject_config` sc on sc.subjectid=s.id')
      // .join('`think_or_subject_childclass` sl on sc.subjectchildclassid=sl.id')
      .where({ 's.departmentid': shopid, 's.isdisable': zt, 's.name|s.remarks|b.name|c.name': ['like', '%' + search + '%'] })
      .page(pages, limits)
      .order('s.id DESC')
      .countSelect();

    return this.json(data);
  }

  async getsubjectconfigAction() {
    const subjectid = this.post().subjectid;
    const shopid = this.userinfo.departmentid;
    const data = await this.model('or_subject_config')
      .alias('sc')
      .field('sc.*,sl.name')
      .join('`think_or_subject_childclass` sl on sc.subjectchildclassid=sl.id')
      .where({ 'sc.subjectid': subjectid, 'sc.departmentid': shopid, 'sc.type': 2 })
      .select();

    return this.json(data);
  }

  async getcategoryAction() {
    const categoryid = JSON.parse(this.post('id'));
    let data = [];
    if (!think.isEmpty(categoryid)) {
      data = await this.model('or_subjectcategory').where({ id: ['IN', categoryid] }).select();
    }
    return this.json(data);
  }

  // 新增、编辑项目
  async addeditAction() {
    const subInfo = this.post().subInfo;
    const subConfig = this.post().subConfig;
    const orid = this.userinfo.departmentid;
    const addtime = Math.round(new Date().valueOf() / 1000);

    const repeat = await this.model('or_subject').where('departmentid=' + orid + ' AND (name="' + subInfo.name + '" OR number="' + subInfo.number + '") AND id!="' + subInfo.id + '"').select();

    if (!think.isEmpty(repeat)) return this.fail('名称或编号重复');

    // if (data.xstdtype == 1) {
    //   data.xspercent = Number(data.xspercent / 100).toFixed(2);
    //   data.xsfixed = 0;
    // } else {
    //   data.xspercent = 0;
    // }

    // if (data.sgtdtype == 1) {
    //   data.sgpercent = Number(data.sgpercent / 100).toFixed(2);
    //   data.sgfixed = 0;
    // } else {
    //   data.sgpercent = 0;
    // }

    // if (data.khtdtype == 1) {
    //   data.khpercent = Number(data.khpercent / 100).toFixed(2);
    //   data.khfixed = 0;
    // } else {
    //   data.khpercent = 0;
    // }
    const model = this.model('or_subject');
    const addsubConfig = [];
    if (subInfo.id * 1) {
      // 编辑项目
      let flag = true;
      const insertsub = [];
      const updatesub = [];
      const reducesub = [];
      const subconfclassidlists = [];
      const getFieldata = await this.model('or_subject_config').where({ subjectid: subInfo.id, type: 2, departmentid: orid }).getField('subjectchildclassid,id');
      const subconflists = getFieldata.subjectchildclassid;
      const subconfidlists = getFieldata.id;
      subConfig.forEach((v) => {
        subconfclassidlists.push(v.subjectchildclassid);
      });
      subConfig.forEach((v) => {
        if (subconflists.includes(v.subjectchildclassid)) {
          delete (v['name']);
          v['id'] = subconfidlists[subconflists.indexOf(v.subjectchildclassid)];
          updatesub.push(v);
        } else {
          insertsub.push({
            subjectid: subInfo.id,
            subjectchildclassid: v.subjectchildclassid,
            type: 2,
            departmentid: orid,
            // xjyjtype: v.xjyjtype,
            xjyjpercent: v.xjyjpercent,
            // xjyjfixed: v.xjyjfixed,
            xjtctype: v.xjtctype,
            xjtcpercent: v.xjtcpercent,
            xjtcfixed: v.xjtcfixed,
            // khyjtype: v.khyjtype,
            khyjpercent: v.khyjpercent,
            // khyjfixed: v.khyjfixed,
            khtctype: v.khtctype,
            khtcpercent: v.khtcpercent,
            khtcfixed: v.khtcfixed
            // minuscost: v.minuscost
          });
        }
      });
      subconflists.forEach((v) => {
        if (!subconfclassidlists.includes(v)) {
          reducesub.push(v);
        }
      });
      await model.transaction(async() => {
        try {
          const upsubIfnum = await model.where({ id: subInfo.id }).update(subInfo);
          if (insertsub.length !== 0) {
            const return1 = await this.model('or_subject_config').db(model.db()).addMany(insertsub);
            if (!return1) { flag = false };
          }
          if (updatesub.length !== 0) {
            const return2 = await this.model('or_subject_config').db(model.db()).updateMany(updatesub);
            if (!return2) { flag = false };
          }
          if (reducesub.length !== 0) {
            const return3 = await this.model('or_subject_config').db(model.db()).where({ subjectid: subInfo.id, subjectchildclassid: ['in', reducesub], type: 2, departmentid: orid }).delete();
            if (!return3) { flag = false };
          }
          if (upsubIfnum && flag) {
            await model.commit();
            return this.success('更新成功!');
          } else {
            await model.rollback();
            return this.fail('更新失败!');
          }
        } catch (e) {
          await model.rollback();
          return this.fail('更新失败!');
        }
      });
    } else {
      // 添加项目
      const addsubInfo = {
        name: subInfo.name,
        departmentid: orid,
        categoryid: subInfo.categoryid,
        brandid: subInfo.brandid,
        price: subInfo.price,
        usetime: subInfo.usetime,
        remarks: subInfo.remarks,
        addtime: addtime,
        number: subInfo.number
        // xstdtype: data.xstdtype,
        // xspercent: data.xspercent,
        // xsfixed: data.xsfixed,
        // sgtdtype: data.sgtdtype,
        // sgpercent: data.sgpercent,
        // sgfixed: data.sgfixed,
        // khtdtype: data.khtdtype,
        // khpercent: data.khpercent,
        // khfixed: data.khfixed
      };
      await model.transaction(async() => {
        try {
          // 写入数据库
          const subjectid = await model.add(addsubInfo);
          subConfig.forEach((v) => {
            addsubConfig.push({
              subjectid: subjectid,
              subjectchildclassid: v.subjectchildclassid,
              type: 2,
              departmentid: orid,
              // xjyjtype: v.xjyjtype,
              xjyjpercent: v.xjyjpercent,
              // xjyjfixed: v.xjyjfixed,
              xjtctype: v.xjtctype,
              xjtcpercent: v.xjtcpercent,
              xjtcfixed: v.xjtcfixed,
              // khyjtype: v.khyjtype,
              khyjpercent: v.khyjpercent,
              // khyjfixed: v.khyjfixed,
              khtctype: v.khtctype,
              khtcpercent: v.khtcpercent,
              khtcfixed: v.khtcfixed
              // minuscost: v.minuscost
            });
          });
          // 写入数据库
          const subjectconfigid = await this.model('or_subject_config').db(model.db()).addMany(addsubConfig);
          if (subjectid && subjectconfigid) {
            await model.commit();
            return this.success('添加成功!');
          } else {
            await model.rollback();
            return this.fail('添加失败!');
          }
        } catch (e) {
          await model.rollback();
          return this.fail('添加失败！');
        }
      });
    }
  }

  // 选择项目
  async selectsubjectAction() {
    const cardid = this.get('cardid');
    const selectsub = await this.model('or_subject')
      .alias('s')
      .join('`think_or_subjectcategory` c on c.id = s.categoryid')
      .field('s.*,c.name as cname')
      .where({ 's.departmentid': this.userinfo.departmentid, 's.isdisable': 0 })
      .select();
    const validity = await this.model('or_card').where({ id: cardid }).getField('validity');
    for (var i = 0, selectlen = selectsub.length; i < selectlen; i++) {
      selectsub[i]['validity'] = validity[0];
    }
    const relist = {
      'draw': '',
      'data': selectsub,
      'breadcrumb': ''
    };
    return this.json(relist);
  }

  // 停用或启用项目
  async subjectstatusAction() {
    const id = this.post('id');
    const st = this.post('st');
    const shiyong = await this.ispull(id);
    if (!think.isEmpty(shiyong)) {
      return this.fail(shiyong.msg);
    }
    const res = await this.model('or_subject').where({ id: id }).update({ isdisable: st });
    if (st * 1) {
      return res ? this.success('停用成功') : this.fail('停用失败');
    } else {
      return res ? this.success('启用成功') : this.fail('启用失败');
    }
  }

  // 获取机构下的项目分类列表
  async subjectcategorylistAction() {
    const shopid = this.userinfo.departmentid;
    const clist = await this.model('or_subjectcategory').where({ departmentid: shopid, pid: ['!=', 0], isdisable: 0 }).select();
    const blist = await this.model('or_brand').where({ departmentid: shopid }).select();
    const data = {
      cs: clist,
      bs: blist
    };
    return this.json(data);
  }

  async getsubjectcategorylistAction() {
    const shopid = this.userinfo.departmentid;
    const slist = await this.model('or_subjectcategory').where({ departmentid: shopid, pid: ['!=', 0] }).select();
    const blist = await this.model('or_brand').where({ departmentid: shopid }).select();
    const data = {
      cs: slist,
      bs: blist
    };
    return this.json(data);
  }

  // 如果当前项目被下属分店拉取，则机构不能操作当前项目
  async ispull(subjectid) {
    const isuse = await this.model('or_shop_subject').where({ subjectid: subjectid }).select();
    if (!think.isEmpty(isuse)) return { msg: '当前项目以被分店拉取' };
    else return false;
  }

  // 保存项目的详细信息
  async saveSubjectInfoAction() {
    const data = this.post();
    data.banner = JSON.stringify(data.banner);
    const res = await this.model('or_subject').where({ id: data.subjectid }).update(data);
    return res ? this.success('操作成功') : this.fail('操作失败');
  }

  // 获取项目的详细信息
  async getSubjectInfoAction() {
    const subjectid = this.get().id;
    const info = await this.model('or_subject').where({ id: subjectid }).find();
    if (info.banner) {
      info.banner = JSON.parse(info.banner);
    }
    return this.json(info);
  }

  // 获取项目下子类
  async getSubjectChildClassAction() {
    const orid = this.userinfo.departmentid;
    const info = await this.model('or_subject_childclass').where({ departmentid: orid, type: 2 }).select();
    return this.json(info);
  }
}
